package com.itheima.web;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收用户数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //因为UserMapper中add方法返回的是User对象，所以要封装对象
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);

        //2.调用mapper 根据用户名查询用户对象
        //2.1获取SqlSessionFactory对象（从官网直接copy）
        /*String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);*/

        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

        //2.2获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //2.3获取Mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //2.4调用方法
        User u = mapper.selectByUsernames(username);

        //2.5判断User是否存在
        if(u == null){
            //用户不存在，添加用户
            mapper.add(user);

            //提交事务
            sqlSession.commit();

            //释放资源
            sqlSession.close();
        }else{
            //用户存在,告诉用户提示信息
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("用户名已存在");
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
/**
 * 创建SqlSeesionFactory代码优化
 * 问题：
 * 1.代码重复->工具类
 * 2.SqlSessionFactory工厂只创建一次，不要重复创建->静态代码块
 */